<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { searchEmployees, addEmployee, updateEmployee, deleteEmployee } from '../api/employeeApi.js';
import { findAllDepartments } from '../api/departmentApi.js'; // 我们需要部门列表

// ================== 状态定义 ==================
const employeeList = ref([]);
const departmentList = ref([]);
const searchParams = ref({
  name: '',
  gender: '',
  deptId: null,
  dateRange: [] // [beginDate, endDate]
});
const dialogVisible = ref(false);
const isEdit = ref(false);
const form = ref({});
const formRef = ref(null); // 表单引用

// ================== 数据加载 ==================
const loadEmployees = async () => {
  const params = {
    name: searchParams.value.name || null,
    gender: searchParams.value.gender || null,
    deptId: searchParams.value.deptId || null,
    beginDate: searchParams.value.dateRange ? searchParams.value.dateRange[0] : null,
    endDate: searchParams.value.dateRange ? searchParams.value.dateRange[1] : null,
  };
  const response = await searchEmployees(params);
  employeeList.value = response.data.data;
};

const loadDepartments = async () => {
  const response = await findAllDepartments();
  departmentList.value = response.data.data.filter(d => d.status === 1); // 只显示启用的部门
};

onMounted(() => {
  loadEmployees();
  loadDepartments();
});

// ================== 辅助函数 ==================
// 根据部门ID查找部门名称
const getDepartmentName = (deptId) => {
  const dept = departmentList.value.find(d => d.deptId === deptId);
  return dept ? dept.name : '未分配';
};

// 计算年龄
const calculateAge = (birthDate) => {
  if (!birthDate) return 'N/A';
  const birth = new Date(birthDate);
  const today = new Date();
  let age = today.getFullYear() - birth.getFullYear();
  const m = today.getMonth() - birth.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
};

// ================== 事件处理 ==================
const handleSearch = () => {
  loadEmployees();
};

const handleReset = () => {
  searchParams.value = { name: '', gender: '', deptId: null, dateRange: [] };
  loadEmployees();
};

const handleAdd = () => {
  isEdit.value = false;
  form.value = {
    name: '',
    username: '',
    password: '',
    gender: '男',
    status: 1,
    deptId: null
  };
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  form.value = { ...row };
  dialogVisible.value = true;
};

const handleStatusChange = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const text = newStatus === 1 ? '启用' : '锁定';
  await updateEmployee({ ...row, status: newStatus });
  ElMessage.success(`${text}成功!`);
  loadEmployees();
};


const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`你确定要删除员工 [${row.name}] 吗?`, '危险操作', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'error',
    });
    await deleteEmployee(row.employeeId);
    ElMessage.success('删除成功!');
    loadEmployees();
  } catch (error) {
    ElMessage.info('已取消删除');
  }
};

const submitForm = async () => {
  // 可以在这里添加更多表单校验，比如密码确认
  if (isEdit.value) {
    await updateEmployee(form.value);
    ElMessage.success('更新成功!');
  } else {
    const res = await addEmployee(form.value);
    if(res.data.code === 200){
      ElMessage.success('添加成功!');
    } else {
      ElMessage.error(res.data.msg);
    }
  }
  dialogVisible.value = false;
  loadEmployees();
};
</script>

<template>
  <div>
    <el-card shadow="never" style="margin-bottom: 15px;">
      <el-form :model="searchParams" inline>
        <el-form-item label="员工姓名">
          <el-input v-model="searchParams.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchParams.gender" placeholder="请选择性别" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="searchParams.deptId" placeholder="请选择部门" clearable>
            <el-option v-for="dept in departmentList" :key="dept.deptId" :label="dept.name" :value="dept.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职日期">
          <el-date-picker v-model="searchParams.dateRange" type="daterange" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div style="margin-bottom: 15px;">
      <el-button type="primary" @click="handleAdd">新增员工</el-button>
    </div>

    <el-table :data="employeeList" border stripe>
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column label="年龄" width="80">
        <template #default="{ row }">{{ calculateAge(row.birthDate) }}</template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="salary" label="薪水" width="120" />
      <el-table-column label="部门">
        <template #default="{ row }">{{ getDepartmentName(row.deptId) }}</template>
      </el-table-column>
      <el-table-column prop="hireDate" label="入职日期" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '在职' : '锁定' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'" @click="handleStatusChange(row)">
            {{ row.status === 1 ? '锁定' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑员工' : '新增员工'" width="50%">
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="姓名" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="登录账号" :disabled="isEdit" required>
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" required>
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="form.deptId" placeholder="请选择部门">
            <el-option v-for="dept in departmentList" :key="dept.deptId" :label="dept.name" :value="dept.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="form.birthDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="入职日期">
          <el-date-picker v-model="form.hireDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="薪水">
          <el-input-number v-model="form.salary" :precision="2" :step="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>